//
//  XHomeViewController.swift
//  WeiBoReDo
//
//  Created by 放学跟鸽走 on 2017/4/8.
//  Copyright © 2017年 放学跟鸽走. All rights reserved.
//

import UIKit
/// 定义全局常量
///原创微博的cellID
fileprivate let originalCellId = "originalCellId"
///被转发微博的cellID
fileprivate let retweetedCellId = "retweetedCellId"
/// 主页模块
class XHomeViewController: XBaseController {
    
    /// 列表视图模型
    lazy var statusListViewModel:XStatusListViewModel = XStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        // 注册通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(browserPhoto),
            name: NSNotification.Name(rawValue: XStatusCellBrowserPhotoNotification),
            object: nil)
        // Do any additional setup after loading the view.
    }
    deinit {
        // 注销通知
        NotificationCenter.default.removeObserver(self)
    }
    /// 浏览照片通知监听方法
    @objc fileprivate func browserPhoto(n: Notification) {
        
        // 1. 从 通知的 userInfo 提取参数
        guard let selectedIndex = n.userInfo?[XStatusCellBrowserPhotoSelectedIndexKey] as? Int,
            let urls = n.userInfo?[XStatusCellBrowserPhotoURLsKey] as? [String],
            let imageViewList = n.userInfo?[XStatusCellBrowserPhotoImageViewsKey] as? [UIImageView]
            else {
                return
        }
        
        // 2. 展现照片浏览控制器
        let vc = HMPhotoBrowserController.photoBrowser(
            withSelectedIndex: selectedIndex,
            urls: urls,
            parentImageViews: imageViewList)
        
        present(vc, animated: true, completion: nil)
    }
    override func loadData() {
        print(#function)
        tableReFreshCtr.beginRefreshing()
        statusListViewModel.loadStatus(isPull: false) { [weak self](needFresh) in
            
            if needFresh{
                self?.myTableView?.reloadData()
            }
            self?.tableReFreshCtr.endRefreshing()
        }
    }
    override func loadMore() {
        print(#function)
        statusListViewModel.loadStatus(isPull: true) { (needFresh) in
            
            if needFresh{
                self.myTableView?.reloadData()
            }
        }
        isPullUp = false
    }
    func enterFriends(){
        print(#function)
        navigationController?.pushViewController(XFlowerListViewController(), animated: true)
        
    }
    
}

// MARK: - UI搭建
fileprivate extension XHomeViewController{
    ///设置UI
    func setupUI(){
        setupTableView()
        setupNav()
    }
    func setupNav(){
        navBarItem.leftBarButtonItem = UIBarButtonItem(title: "朋友", target: self, action: #selector(enterFriends))
    }
    func setupTableView(){
        myTableView?.register(XStatusOriginCell.self, forCellReuseIdentifier: originalCellId)
        myTableView?.register(XStatusRetweetCell.self, forCellReuseIdentifier: retweetedCellId)
        myTableView?.rowHeight = UITableViewAutomaticDimension
        myTableView?.estimatedRowHeight = 300
        //取消分隔线
        myTableView?.separatorStyle = .none
    }
}

// MARK: - tableView 代理及数据源方法实现
extension XHomeViewController{
    //MARK: TableView DATA SOURCE
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.listModel.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let vm = statusListViewModel.listModel[indexPath.row]
        //设置对应的cellId
        let isRetweet = (vm.status.retweeted_status != nil)
        if isRetweet{
            let cell = tableView.dequeueReusableCell(withIdentifier: retweetedCellId, for: indexPath) as? XStatusRetweetCell
             cell?.viewModel = vm
            cell?.delegate = self
            return cell ?? XStatusRetweetCell()
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: originalCellId, for: indexPath) as? XStatusOriginCell
            cell?.viewModel = vm
            cell?.delegate = self
            return cell ?? XStatusOriginCell()
        }
        
        
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // 1. 根据 indexPath 获取视图模型
        let vm = statusListViewModel.listModel[indexPath.row]
        
        // 2. 返回计算好的行高
        return vm.rowHeight
    }
}
// MARK: - WBStatusCellDelegate
extension XHomeViewController: WBStatusCellDelegate {
    
    func statusCellDidSelectedURLString(cell: XStatusOriginCell, urlString: String) {
        
        let vc = XWebViewController()
        
        vc.urlString = urlString
        
        navigationController?.pushViewController(vc, animated: true)
    }
}
extension XHomeViewController: WBStatusRetweetCellDelegate{
    
    func statusRetweetCellDidSelectedURLString(cell: XStatusRetweetCell, urlString: String) {
        
        let vc = XWebViewController()
        
        vc.urlString = urlString
        
        navigationController?.pushViewController(vc, animated: true)
    }
}
